package com.five.matebook.utils;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class SettingsStore<T> {
    private static final boolean USE_MMKV = true;
    protected Context context;
    protected final String key;
    private final TypeToken<T> typeToken;
    protected T data;
    public SettingsStore(Context context, String key, TypeToken<T> typeToken) {
        this.context = context;
        this.key = key;
        this.typeToken = typeToken;
        data = load();
    }

    public void save(T newData) {
        data = newData;
        Gson gson = new Gson();
        String s = gson.toJson(data);
        if (!TextUtils.isEmpty(s)) {
            if (USE_MMKV) {
                MmkvUtils.saveString(context, key, s);
            } else {
                SharedPreferencesUtil.saveJsonData(context, key, s);
            }
        }
        notifySetttingChanged();
    }

    private T load() {
        String json;
        if (USE_MMKV) {
            json = MmkvUtils.getString(context, key);
        } else {
            json = SharedPreferencesUtil.getJsonData(context, key);
        }
        if (!TextUtils.isEmpty(json)) {
            Gson gson = new Gson();
            return gson.fromJson(json, typeToken);
        }
        return null;
    }

    public T getData() {
        return data;
    }

    private final List<ICallback> callbackList = new ArrayList<>();
    public synchronized void addCallback(ICallback callback) {
        if (callback == null || callbackList.contains(callback)) {
            return;
        }
        callbackList.add(callback);
    }

    public synchronized void removeCallback(ICallback callback) {
        callbackList.remove(callback);
    }

    protected void notifySetttingChanged() {
        for (ICallback callback : callbackList) {
            callback.onSetttingsChanged();
        }
    }

    public interface ICallback {
        void onSetttingsChanged();
    }
}
